package com.cinemahorairerapido.controller;

import java.io.IOException;
import java.util.List;

import org.json.JSONException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.AsyncTask;

import com.cinemahorairerapido.R;
import com.cinemahorairerapido.ShowTimeTabsFragment;
import com.cinemahorairerapido.bean.Cinema;
import com.cinemahorairerapido.bean.Movie;

public class FindCinemaProgramTask extends AsyncTask<Cinema, Integer, Integer> {

	public static final int DIALOG_TIMEOUT = 101;

	public static final int DIALOG_PARSE_KO = 102;

	private static final Integer RESULT_OK = 0;

	private static final Integer RESULT_KO_JASON = 1;

	private static final Integer RESULT_KO_TIMEOUT = 2;

	private final Activity context;

	private Dialog progressDialog;

	private Cinema currentCinema;

	public FindCinemaProgramTask(Activity parentActivity, Dialog progressDialog) {
		super();
		this.context = parentActivity;
		this.progressDialog = progressDialog;
	}

	@Override
	protected Integer doInBackground(Cinema... value) {

		currentCinema = value[0];

		try {
			List<Movie> movies = AllocineController.getCinemaProgram(currentCinema.getAllocineCode(), currentCinema);
			currentCinema.setProgram(movies);

			return RESULT_OK;

		} catch (IOException e) {
			return RESULT_KO_TIMEOUT;
		} catch (JSONException e) {
			return RESULT_KO_JASON;
		}

	}

	@Override
	protected void onProgressUpdate(Integer... progress) {
		// setProgressPercent(progress[0]);
	}

	@Override
	protected void onPostExecute(Integer result) {

		if (result == FindCinemaProgramTask.RESULT_OK) {
			Intent i = new Intent(context, ShowTimeTabsFragment.class);
			i.putExtra(ShowTimeTabsFragment.PARAM_CINEMA, currentCinema);
			context.startActivity(i);
		}

		// close progress dialog
		if (progressDialog != null) {
			progressDialog.cancel();
			progressDialog = null;
		}

		if (result == FindCinemaProgramTask.RESULT_KO_TIMEOUT) {
			context.showDialog(DIALOG_TIMEOUT);
		} else if (result == FindCinemaProgramTask.RESULT_KO_JASON) {
			context.showDialog(DIALOG_PARSE_KO);
		}
	}

	/**
	 * Create alert dialog for no connection
	 * 
	 * @param activity
	 * @return AlertDialog
	 */
	public static AlertDialog createNoConnectionDialog(Activity activity) {

		return AlertDialogBuilder.createAlertDialog(activity, R.string.alertnoconnectiontitle, R.string.alertnoconnection);
	}

	/**
	 * Create alert dialog for parse KO
	 * 
	 * @param activity
	 * @return AlertDialog
	 */
	public static AlertDialog createJasonParseErrorDialog(Activity activity) {

		return AlertDialogBuilder.createAlertDialog(activity, R.string.alertdatatitle, R.string.alertdata);
	}

}
